package com.zz.apk.utils;


import com.zz.framework.core.ext.LogExtKt;
import com.zz.framework.core.config.GlobalSetting;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadUtil {

    public static final String TAG = "R-DownloadUtil";
    public static final String TEMP = "_temp";

    public void download(final String cacheDir, final String url, final String fileType, final OnDownloadListener listener) {
        try {
            listener.onDownloadPrepare();
            LogExtKt.loge(this,TAG + "download->prepare:" + url);

            File file = new File(FilesUtil.getCacheFilePath(cacheDir, url) + TEMP + FilesUtil.getUrlEnd(url, fileType));
            RandomAccessFile raf;
            long downLoadSize = 0;
//            if (file.exists()) {
//                downLoadSize = file.length();
//                raf = new RandomAccessFile(file, "rwd");
//                raf.seek(downLoadSize);
//            } else {
                if (file.exists()) {
                    file.delete();
                }
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                raf = new RandomAccessFile(file, "rwd");
//            }
            long totalSize = getContentLength(url);
            LogExtKt.loge(this,TAG + "download->start == totalSize:" + totalSize + ",downLoadSize:" + downLoadSize);
            if (downLoadSize == totalSize) {// 判断是否下载完成
                //已经下载完成
                downloadCompleted(file, cacheDir, url, fileType, listener);
                return;
            }
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).
                    addHeader("Range", "bytes=" + downLoadSize + "-" + totalSize)
                    .addHeader("X-Access-Token", GlobalSetting.INSTANCE.getToken())
                    .build();
            Response response = client.newCall(request).execute();
            InputStream ins = response.body().byteStream();
            //上面的就是简单的OKHttp连接网络，通过输入流进行写入到本地
            int len = 0;
            byte[] by = new byte[1024];
            long endTime = System.currentTimeMillis();
            while ((len = ins.read(by)) != -1/* && isDown*/) {//如果下载没有出错并且已经开始下载，循环进行以下方法
                raf.write(by, 0, len);
                downLoadSize += len;
                if (System.currentTimeMillis() - endTime > 1000) {
                    final double dd = downLoadSize / (totalSize * 1.0);
                    DecimalFormat format = new DecimalFormat("#0.00");
                    String value = format.format((dd * 100)) + "%";//计算百分比
                    LogExtKt.loge(this,TAG + "download->progress == " + value);
                    endTime = System.currentTimeMillis();
                    listener.onDownloading((int) (dd * 100), downLoadSize, totalSize);
                }
            }
            response.close();//最后要把response关闭
            // 下载完成
            downloadCompleted(file, cacheDir, url, fileType, listener);
        } catch (Exception e) {
            e.printStackTrace();
            LogExtKt.loge(this,TAG + "download->failed == " + e.getMessage());
            listener.onDownloadFailed(e);
        }
    }

    private void downloadCompleted(File file, String cacheDir, String url, String fileType, OnDownloadListener listener) {
        File fileNew = new File(FilesUtil.getCacheFilePath(cacheDir, url) + FilesUtil.getUrlEnd(url, fileType));
        FilesUtil.fileChannelCopy(file, fileNew);
        file.delete();
        LogExtKt.loge(this,TAG + "download->success == totalSize:" + fileNew.length());
        listener.onDownloadSuccess(fileNew.getAbsolutePath());
    }

    //通过OkhttpClient获取文件的大小
    private long getContentLength(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        long length = response.body().contentLength();
        response.close();
        return length;
    }

    public interface OnDownloadListener {

        void onDownloadPrepare();

        /**
         * 下载成功
         */
        void onDownloadSuccess(String path);

        void onDownloading(int progress, long downLoadSize, long totalSize);

        /**
         * 下载失败
         */
        void onDownloadFailed(Exception e);
    }
}
